package com.lyl.exception.config;

import cn.hutool.core.util.StrUtil;
import com.lyl.exception.common.ErrorResult;
import com.lyl.exception.common.MyException;
import com.lyl.exception.common.Result;
import com.lyl.exception.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @Resource
    private HttpServletRequest request;

    @ExceptionHandler(Throwable.class)
    public Result onExceptionHandler(Exception e){
        String queryStr = request.getQueryString();
        String url = request.getRequestURL() + (StrUtil.isBlank(queryStr) ? "" : "?" + queryStr);
        log.error("异常URL: {}" , url,e);
        return new ErrorResult().setErrorURL(url)
                .setErrorMsg(e.getMessage())
                .setErrorName(e.getClass().getName());
    }

    //处理自定义异常
    @ExceptionHandler(MyException.class)
    public Result onMyException(MyException e){
        String queryStr = request.getQueryString();
        String url = request.getRequestURL() + (StrUtil.isBlank(queryStr) ? "" : "?" + queryStr);
        log.error("异常URL: {}" , url,e);
        return new ErrorResult(ResultCode.BUSINESS_EXCEPTION.getCode(), e.getMsg())
                .setErrorURL(url)
                .setErrorMsg(e.getMessage())
                .setErrorName(e.getClass().getName());
    }
}
